package com.suse.warmstill.service.impl;

import com.alibaba.fastjson.JSON;
import com.suse.warmstill.common.enums.RedisEnum;
import com.suse.warmstill.entity.TbIndexPicture;
import com.suse.warmstill.mapper.TbIndexPictureMapper;
import com.suse.warmstill.service.BaseService;
import com.suse.warmstill.service.IndexPictureService;
import com.suse.warmstill.vo.IndexPitureVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 黄靖
 * @author 2022-11-05 11:15
 * description:
 **/
@Service
public class IndexPictureServiceImpl implements IndexPictureService, BaseService<IndexPitureVO, TbIndexPicture> {

    @Resource
    private TbIndexPictureMapper pictureMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<IndexPitureVO> listAll() {
        /*
         * 先从redis中查询  ，，没有的话 从数据库查
         * */
        final String list = redisTemplate.opsForValue().get(RedisEnum.INDEX_PICURE);

        List<IndexPitureVO> indexPitureVOS = null;


        if (StringUtils.isNotEmpty(list)) {
            indexPitureVOS = JSON.parseArray(list, IndexPitureVO.class);
            return indexPitureVOS;
        } else {

            List<TbIndexPicture> tbIndexPictures = pictureMapper.selectList(null);
            List<IndexPitureVO> all = new ArrayList<>();

            tbIndexPictures.forEach((entity) -> {
                all.add(toVo(entity));
            });

            redisTemplate.opsForValue().set(RedisEnum.INDEX_PICURE, JSON.toJSONString(all), 30, TimeUnit.HOURS);
        }

        final String sss = redisTemplate.opsForValue().get(RedisEnum.INDEX_PICURE);
        indexPitureVOS = JSON.parseArray(sss, IndexPitureVO.class);


        return indexPitureVOS;


    }


    @Override
    public TbIndexPicture toEntity(IndexPitureVO vo) {
        final TbIndexPicture tbIndexPicture = new TbIndexPicture();
        tbIndexPicture.setAvator(vo.getAvator());
        tbIndexPicture.setPictureAdress(vo.getPictureAdress());
        tbIndexPicture.setContent(vo.getContent());
        tbIndexPicture.setName(vo.getName());
        tbIndexPicture.setPath(vo.getPath());
        tbIndexPicture.setId(vo.getId());

        return tbIndexPicture;
    }

    @Override
    public IndexPitureVO toVo(TbIndexPicture entity) {
        final IndexPitureVO indexPitureVO = new IndexPitureVO();
        indexPitureVO.setAvator(entity.getAvator());
        indexPitureVO.setPictureAdress(entity.getPictureAdress());
        indexPitureVO.setContent(entity.getContent());
        indexPitureVO.setId(entity.getId());
        indexPitureVO.setName(entity.getName());
        indexPitureVO.setPath(entity.getPath());


        return indexPitureVO;
    }
}
